package com.ruipeng.shengyapo.service.impl;

import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.response.AlipayTradeRefundResponse;
import com.ruipeng.shengyapo.controller.WeChatConstans;
import com.ruipeng.shengyapo.dao.OrderMapper;
import com.ruipeng.shengyapo.dao.UserMapper;
import com.ruipeng.shengyapo.pay.alipay.config.AlipayConfig;
import com.ruipeng.shengyapo.pay.alipay.util.AlipayNotify;
import com.ruipeng.shengyapo.pay.wx.RequestHandler;
import com.ruipeng.shengyapo.pay.wx.TenpayUtil;
import com.ruipeng.shengyapo.pay.wx.http.HttpClientConnectionManager;
import com.ruipeng.shengyapo.pay.wx.refund.RefundUtil;
import com.ruipeng.shengyapo.service.OrderService;
import com.ruipeng.shengyapo.utils.HttpUtils;
import com.ruipeng.shengyapo.utils.NumberUtils;
import com.ruipeng.shengyapo.utils.ObjUtils;
import net.sf.json.JSONObject;
import net.sf.json.util.JSONUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.net.ssl.SSLContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.security.KeyStore;
import java.util.*;

/**
 * Created by tu_pei on 17/6/7.
 */

@Service
public class OrderServiceImpl implements OrderService{

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private UserMapper userMapper;

    @Override
    public int initAddRiDingOrder(Map<String, Object> params) {
        return orderMapper.initAddRiDingOrder(params);
    }

    @Override
    public List<Map<String, Object>> getUserOrderByUserId(Map<String, Object> params) {
        params.put("ridingStatus","0");
        return orderMapper.getUserOrderByUserId(params);
    }

    /**
     * 支付生成订单号
     *
     * @param params
     */
    @Override
    public Map<String,Object> addOrderInfo(Map<String, Object> params) {
        String orderNo = ObjUtils.getNowDate() + ObjUtils.randomNumeric(4)+"00100"+ObjUtils.randomNumeric(6)+"00"+ObjUtils.randomNumeric(4);
        params.put("rechgId",orderNo);
        params.put("otherNo",params.get("otherNo"));
        orderMapper.addOrderInfo(params);
        return params;
    }

    /**
     * 根据订单号查询订单
     *
     * @return
     */
    @Override
    public Map<String, Object> getOrderByOrderNo(Map<String,Object> params) {
        return orderMapper.getOrderByOrderNo(params);
    }


    /**
     * 修改支付订单状态
     *
     * @param orderNo
     * @param orderInfo
     * @return
     */
    @Override
    public int updateOrderByOrderNo(String orderNo, String orderInfo,int tradeStatus,String otherNo,String out_trade_no) {
        return orderMapper.updateOrderByOrderNo(orderNo, orderInfo,tradeStatus,otherNo,out_trade_no);
    }

    /**
     * 微信回调成功，生成订单
     *
     * @param params
     * @return
     */
    @Override
    public int addWxOrderInfo(Map<String, Object> params) {
        return 0;
    }

    /**
     * 获取用户充押金订单信息
     *
     * @param userId
     * @return
     */
    @Override
    public Map<String, Object> getUserOrderDeposit(int userId) {
        return orderMapper.getUserOrderDeposit(userId);
    }

    /**
     * 退押金
     *
     * @param userId
     * @return
     */
    @Override
    public boolean updateUserPayDeposit(HttpServletRequest request, HttpServletResponse response,int userId) {
        int count = 0;
        boolean refundOk = false;
        //获取用户交押金历史信息
        Map<String,Object> userDeposit = getUserOrderDeposit(userId);
        Map<String,Object> userInfo = userMapper.getByUserId(userId);
        BigDecimal userMoney = new BigDecimal(userInfo.get("userAccount").toString());
        if(userDeposit!=null && userMoney.doubleValue() >=0 ){
            Integer tradeType = Integer.parseInt(userDeposit.get("tradeWay").toString());//支付类型 ： 0 微信 ；1支付宝
            Double tradeMoney = Double.parseDouble(userDeposit.get("totalFee").toString());
            String orderNo = userDeposit.get("otherNo").toString();
            if( tradeType == 0 ){

                String reslut = RefundUtil.wechatRefund(orderNo,tradeMoney);
                if(reslut.equals("FAIL")){
                    return false;
                }
            }else{
                //支付宝退款
            AlipayClient alipayClient = new DefaultAlipayClient
                    ("https://openapi.alipay.com/gateway.do", AlipayConfig.APP_ID,
                            AlipayConfig.private_key,"json",AlipayConfig.input_charset,AlipayConfig.ali_public_key,AlipayConfig.sign_type);
            AlipayTradeRefundRequest aliRequest = new AlipayTradeRefundRequest();

            aliRequest.setBizContent("{" +
                    "\"trade_no\":\""+orderNo+"\"," +
                    "\"refund_amount\":"+tradeMoney+"" +
                    "  }");
                try{
                    AlipayTradeRefundResponse aliResponse = alipayClient.execute(aliRequest);
                    if(aliResponse.isSuccess()){
                        System.out.println("退款成功");
                    } else {

                        System.out.println("调用失败");
                        return false;
                    }
                    System.out.println(JSONObject.fromObject(aliResponse));
                }catch (Exception e){
                    e.printStackTrace();
                }
            }

            Map<String,Object> orderMap = new HashMap<String,Object>();
            orderMap.put("userId",userId);
            orderMap.put("rechgId",userDeposit.get("rechgId"));
            orderMap.put("rechargeType",3);
            orderMap.put("rechargeWay",userDeposit.get("tradeWay"));
            orderMap.put("rechgrgeAmount",tradeMoney);
            orderMap.put("tradeInfo","");
            orderMap.put("tradeStatus",1);
            orderMap.put("otherNo",orderNo);
            orderMapper.addOrderInfo(orderMap);
            //修改用户押金字段
            Map<String,Object> updateUserMap = new HashMap<String,Object>();
            updateUserMap.put("userId",userId);
            updateUserMap.put("deposit",0);
            count = userMapper.updateUserInfo(updateUserMap);
            return true;
        }else{
            return false;
        }
    }

    /**
     * @param ridingOrderId
     * @return
     */
    @Override
    public Map<String, Object> getUserRidingPaths(int ridingOrderId) {
        return orderMapper.getUserRidingPaths(ridingOrderId);
    }
}
